/**
 * 
 */
package com.alstudio.ui.module.notice;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.core.message.ALMessageNotificationManager;
import com.alstudio.core.message.LoadMessageCallback;
import com.alstudio.core.message.note.NoteMessageManager;
import com.alstudio.core.message.system.SystemMessageManager;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.ui.module.notice.UserNoticeAdapter.AddOnIconClickListener;
import com.alstudio.ui.module.user.UserHomePageAcitivty;
import com.alstudio.utils.android.color.ALColorUtils;
import com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.ALAudioPlayTaskCallback;
import com.alstudio.utils.android.net.download.ALHttpDownloadTask.ALHttpDownloadErrorCode;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.listener.AlDialogOnClickListener;
import com.alstudio.view.listview.PullRefreshAndLoadMoreView;
import com.alstudio.view.listview.PullRefreshAndLoadMoreView.RankViewLoadStateListener;
import com.alstudio.view.tableview.ALBasicListItem;
import com.loovee.imaohu.R;
import com.nhaarman.listviewanimations.itemmanipulation.AnimateDismissAdapter;
import com.nhaarman.listviewanimations.itemmanipulation.OnDismissCallback;

/**
 * 留言信箱
 * 
 * @author alonso lee
 * 
 */
public class UserNoticeActivity extends TitleBarActivity implements
		RankViewLoadStateListener, OnItemClickListener, AddOnIconClickListener,
		ALAudioPlayTaskCallback {

	private ALBasicListItem systemNoticeItem;

	// 显示用户数据的view
	private PullRefreshAndLoadMoreView listview;

	private ArrayList<ALMessage> msgs;

	private UserNoticeAdapter adapter;

	private boolean isEditing = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(this, getClass().getSimpleName());
		initData();
	}

	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setCenterTextViewMessage(R.string.TxtUserMessage);
		setTitleBarActivityContentView(R.layout.user_note_notice_layout);
		rightUseImageButton(true);
		setRightButtonImageSrc(R.drawable.personal_title_icon_set);
		setRightButtonClickListener(this);

		listview = (PullRefreshAndLoadMoreView) findViewById(R.id.listview);
		// 禁止下拉刷新
		listview.disablePullRefresh();
		// 不要声音
		listview.setSoundEffectsEnabled(false);

		msgs = new ArrayList<ALMessage>();
		adapter = new UserNoticeAdapter(getApplicationContext(), msgs);
		adapter.setAddOnIconClickListener(this);
		adapter.setDeleteIconClickListener(deleteIconClickListener);
		listview.setLoadStateListener(this);
		listview.setItemClickListener(this);

		noteAnimateDismissAdapter = new AnimateDismissAdapter(adapter,
				NoteOnDismissCallback);
		noteAnimateDismissAdapter.setAbsListView(listview.getListView());

		listview.setAdapter(adapter);

		// 初始化系统消息布局
		initSystemNoticeItem();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		// 读取未读留言
		loadUnReadSystemNoticeCount();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ALLocalEnv.getLocalEnv().setAudioPlayerCallback(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		ALLocalEnv.getLocalEnv().setAudioPlayerCallback(null);
		ALLocalEnv.getLocalEnv().stopAudio();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.aLBasicListItem1:
			gotoSystemNoticeActivity();
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#invokeRightBtnClick()
	 */
	@Override
	protected void invokeRightBtnClick() {
		// TODO Auto-generated method stub
		super.invokeRightBtnClick();
		invokeEditBtnClickEvent();
	}

	private void gotoSystemNoticeActivity() {
		Intent i = new Intent(this, SystemNoticeActivity.class);
		startActivity(i);
	}

	private void invokeEditBtnClickEvent() {

		isEditing = !isEditing;

		adapter.setShowDelete(isEditing);
		adapter.notifyDataSetChanged();

		if (!isEditing) {
			setRightButtonImageSrc(R.drawable.personal_title_icon_set);
		} else {
			setRightButtonImageSrc(R.drawable.friend_title_icon_confirm);
		}
	}

	private void initSystemNoticeItem() {
		systemNoticeItem = (ALBasicListItem) findViewById(R.id.aLBasicListItem1);
		systemNoticeItem.setDrawable(R.drawable.mail_icon_broadcast);

		systemNoticeItem.mini_title.setTextColor(ALColorUtils.getColor(
				ALLocalEnv.getLocalEnv(), R.color.list_age_color));

		systemNoticeItem.title
				.setBackgroundResource(R.drawable.friend_mutual_icon_massage);

		systemNoticeItem.title.setTextAppearance(getApplicationContext(),
				R.style.content_page_large_count_text);

		systemNoticeItem.title.setGravity(Gravity.CENTER);

		goneView(systemNoticeItem.title);

		systemNoticeItem.mini_title.setText(R.string.TxtSystemNotice);
		showView(systemNoticeItem.mini_title);

		systemNoticeItem.title.setTextColor(ALColorUtils.getColor(
				ALLocalEnv.getLocalEnv(), R.color.white));

		systemNoticeItem.setOnClickListener(this);
	}

	/**
	 * 显示未读系统消息数
	 * 
	 * @param count
	 */
	private void updateSystemNoticeItem(int count) {

		systemNoticeItem.title.setText("" + count);
		if (count > 0) {
			showView(systemNoticeItem.title);
		} else {
			goneView(systemNoticeItem.title);
		}

	}

	/**
	 * 读取未读系统消息数
	 */
	private void loadUnReadSystemNoticeCount() {
		SystemMessageManager.getSystemMessageManager()
				.loadUnReadSystemMessageCount(
						loadUnReadSystemMessageCountCallback);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		loadNoteMessage();
		new Thread() {
			public void run() {
				ALMessageNotificationManager
						.getDefaultALMessageNotificationManager()
						.cancelUserMessageNotification();
			};
		}.start();

	}

	/**
	 * 读取留言消息
	 */
	private void loadNoteMessage() {
		NoteMessageManager.getNoteMessageManager().loadNoteMessage(msgs.size(),
				mLoadNoteMessageCallback);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.view.listview.PullRefreshAndLoadMoreView.
	 * RankViewLoadStateListener
	 * #onLoadMore(com.alstudio.view.listview.PullRefreshAndLoadMoreView)
	 */
	@Override
	public void onLoadMore(PullRefreshAndLoadMoreView view) {
		// TODO Auto-generated method stub
		loadNoteMessage();
	}

	@Override
	public void onRefresh(PullRefreshAndLoadMoreView view) {
		// TODO Auto-generated method stub

	}

	private LoadMessageCallback mLoadNoteMessageCallback = new LoadMessageCallback() {

		@Override
		public void onLoadCompleted(Object obj) {
			// TODO Auto-generated method stub
			@SuppressWarnings("unchecked")
			ArrayList<ALMessage> temp = (ArrayList<ALMessage>) obj;
			msgs.addAll(temp);
			// if (temp.size() > 0) {
			// adapter.notifyDataSetChanged();
			// }
			if (temp.size() == 0
					|| temp.size() < ALLocalEnv.LOAD_MORE_COUNT_PER_TIME) {
				// 没有更多了
				listview.updateLoadMoreState(false);
			}
			listview.onLoadMoreCompleted();

			temp.clear();
			temp = null;

			if (msgs.size() == 0) {
				listview.showNoDataInfo(R.drawable.me_myphone_icon_empty01,
						getString(R.string.TxtNoCallHistoryHint));
			} else {
				listview.showRefereshListView();
				adapter.notifyDataSetChanged();
			}

		}
	};

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
		// TODO Auto-generated method stub
		if (isEditing)
			return;
		if (id == -1) {
			// 点击的是headerView或者footerView
			return;
		}
		int realPosition = (int) id;
		ALMessage info = msgs.get(realPosition);
		if (info == null)
			return;
		User u = new User();
		u.setJid(info.getFrom());
		u.setNick(info.getFromNick());

		Intent i = new Intent(UserNoticeActivity.this,
				UserHomePageAcitivty.class);
		i.putExtra("user", u);
		startActivity(i);
	}

	private ALMessage prePlayMsg = null;

	@Override
	public void onAddOnIconClick(Object obj) {
		// TODO Auto-generated method stub
		ALMessage msg = (ALMessage) obj;
		boolean isPlayRequest = false;
		if (prePlayMsg != null) {
			if (prePlayMsg == msg) {
				msg.setPlaying(!prePlayMsg.isPlaying());
			} else {
				prePlayMsg.setPlaying(false);
				msg.setPlaying(!msg.isPlaying());
			}
		} else {
			msg.setPlaying(!msg.isPlaying());
		}

		if (msg.isPlaying()) {
			isPlayRequest = true;
		}

		// 设为已读
		msg.setDisplayed(true);

		adapter.notifyDataSetChanged();
		prePlayMsg = msg;
		ALLocalEnv.getLocalEnv().stopAudio();
		if (isPlayRequest) {
			ALLocalEnv.getLocalEnv().playAudio(msg.getAudioFaceId());
		}

		NoteMessageManager.getNoteMessageManager().setNoteReadedById(
				msg.getMsgId());
	}

	private void updateAdapterPlayState(boolean isPlaying) {
		if (prePlayMsg == null)
			return;
		prePlayMsg.setPlaying(isPlaying);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void handleNewNoteMessageEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleNewNoteMessageEvent(msg);
		// 新消息
		addNewNoteMessage(msg);
	}

	private void addNewNoteMessage(ALMessage msg) {
		msgs.add(0, msg);
		listview.showRefereshListView();
		adapter.notifyDataSetChanged();

	}

	@Override
	public void handleNewSystemMessageEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleNewSystemMessageEvent(msg);
		loadUnReadSystemNoticeCount();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		menu.clear();
		menu.add(Menu.FIRST, Menu.FIRST + 1, Menu.FIRST + 1,
				getString(R.string.TxtAllRead));
		menu.add(Menu.FIRST + 1, Menu.FIRST + 2, Menu.FIRST + 2,
				getString(R.string.TxtAllDelete));
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		boolean isDelete = false;
		if (item.getItemId() == Menu.FIRST + 1) {

		} else if (item.getItemId() == Menu.FIRST + 2) {
			isDelete = true;
		}
		showMenuOptDialog(isDelete);
		return super.onOptionsItemSelected(item);
	}

	private void showMenuOptDialog(final boolean isDelete) {
		// 全部已读
		String msg = getString(R.string.TxtAllReadInfo);
		if (isDelete) {
			msg = getString(R.string.TxtAllDeleteInfo);
		}

		AlertDialogCreator mDialogCreator = AlertDialogCreator
				.createTwoButtonNormalDialog(this, false);
		mDialogCreator.setLeftKeyListener(new AlDialogOnClickListener() {

			@Override
			public void onClick() {
				if (isDelete) {
					NoteMessageManager.getNoteMessageManager().deleteAllNote();
					msgs.clear();
					listview.showNoDataInfo(R.drawable.me_myphone_icon_empty01,
							getString(R.string.TxtNoCallHistoryHint));
				} else {
					NoteMessageManager.getNoteMessageManager()
							.setAllNoteReaded();
					for (ALMessage msg : msgs) {
						msg.setDisplayed(true);
					}
					adapter.notifyDataSetChanged();

				}
			}
		});

		mDialogCreator.setMessage(msg);

		mDialogCreator.showDialog();
	}

	private LoadMessageCallback loadUnReadSystemMessageCountCallback = new LoadMessageCallback() {

		@Override
		public void onLoadCompleted(Object obj) {
			// TODO Auto-generated method stub
			int count = (Integer) obj;
			updateSystemNoticeItem(count);
		}
	};

	/**************************************** 删除 ***********************************************/
	private AnimateDismissAdapter noteAnimateDismissAdapter;;

	private AddOnIconClickListener deleteIconClickListener = new AddOnIconClickListener() {

		@Override
		public void onAddOnIconClick(Object obj) {
			// TODO Auto-generated method stub
			// 删除指定位置的记录
			int pos = (Integer) obj;
			noteAnimateDismissAdapter.animateDismiss(pos);
		}
	};

	private OnDismissCallback NoteOnDismissCallback = new OnDismissCallback() {

		@Override
		public void onDismiss(AbsListView arg0, int[] reverseSortedPositions) {
			// TODO Auto-generated method stub
			for (int position : reverseSortedPositions) {
				if (position < msgs.size()) {
					ALMessage msg = msgs.remove(position);
					adapter.notifyDataSetChanged();
					// 从数据库中删除
					NoteMessageManager.getNoteMessageManager().deleteNoteById(
							msg.getMsgId());

					if (msgs.size() < 10) {
						// loadTempCallHistory();
						// 重新读取数据库中的剩余数据
						loadNoteMessage();
					}

				}
			}
		}
	};

	/**************************************** 删除 ***********************************************/

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicPlay()
	 */
	@Override
	public void onMusicPlay() {
		// TODO Auto-generated method stub
		updateAdapterPlayState(true);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicStop()
	 */
	@Override
	public void onMusicStop() {
		// TODO Auto-generated method stub
		updateAdapterPlayState(false);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicPause()
	 */
	@Override
	public void onMusicPause() {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicError()
	 */
	@Override
	public void onMusicError() {
		// TODO Auto-generated method stub
		updateAdapterPlayState(false);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALMusicPlayerCallback#
	 * onMusicProgressChanged(int)
	 */
	@Override
	public void onMusicProgressChanged(int second) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.
	 * ALAudioPlayTaskCallback#onUpdateProcess(int)
	 */
	@Override
	public void onUpdateProcess(int percent) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.
	 * ALAudioPlayTaskCallback#onDownloadFinish(java.lang.String)
	 */
	@Override
	public void onDownloadFinish(String path) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.
	 * ALAudioPlayTaskCallback#onPreDownload()
	 */
	@Override
	public void onPreDownload() {
		// TODO Auto-generated method stub
		updateAdapterPlayState(true);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.utils.android.media.audio.player.ALAudioPlayTask.
	 * ALAudioPlayTaskCallback
	 * #onDownloadFail(com.alstudio.utils.android.net.download
	 * .ALHttpDownloadTask.ALHttpDownloadErrorCode)
	 */
	@Override
	public void onDownloadFail(ALHttpDownloadErrorCode code) {
		// TODO Auto-generated method stub
		updateAdapterPlayState(false);
	}

}
